// 1. 创建store对象 存储默认状态0
// 2. 将store对象放在一个全局的 组件可以够的到的地方
// 3. 让组件获取store对象中的状态 并将状态显示在组件中
import { observable, action, runInAction, flow, computed, configure, autorun } from 'mobx'
import axios from 'axios';

// 通过配置强制程序使用action函数更改应用程序中的状态
configure({ enforceActions: 'observed' });

class CounterStore {

  constructor () {
    //检测数据变化 响应函数ß
    autorun (() => {
      try {
        uniqueUsername(this.username)
        console.log('用户名可用')
      }catch (e) {
        console.log(e.message)
      }
    }, {
      delay: 2000
    })
  }

  //通过 observable 把store变为可变化数据
  @observable count = 0;
  @observable users = []
  @observable username = '';

  // increment = () => {
  //   this.count = this.count + 1;
  // }

  // decrement = () => {
  //   this.count = this.count - 1;
  // }

  //action.bound 可以用来自动地将动作绑定到目标对象 改变this 指向
  @action.bound increment() {
    this.count = this.count + 1;
  }

  @action.bound decrement() {
    this.count = this.count - 1;
  }
  //通过 runInAction 更新状态
  @action.bound async getData() {
    let { data } = await axios.get('https://api.github.com/users');
    //异步之后store 操作
    runInAction(() => this.users = data);
  }
  //使用flow 异步更新状态
  // getData = flow(function* () {
  //   let { data } = yield axios.get('https://api.github.com/users');
  //   this.users = data
  // }).bind(this)

  //检测数据 变化
  @computed get getResult() {
    return this.count * 10
  }

  @action.bound changeUsername (username) {
    this.username = username;
  }
  
}

function uniqueUsername (username) {
  return new Promise((resolve, reject) => {
    if (username === 'admin') {
      reject('用户名已经存在')
    }else {
      resolve()
    }
  })
}

const counter = new CounterStore()

export default counter;